<?php
class ss_cli_command_merge extends ss_cli_command {
	protected $schema;
	
	public function __call($func,$args){
		
	}
	
	public function execute(){
		return call_user_func_array(array($this,'schema'),func_get_args());
	}
	
	public function schema(){
		$this->dispatch->output("\n*** Merging Schema files ***");
		if(func_num_args()>0){
			$source=func_get_args();
		} else {
			if(is_array($this->schema)) return $this->schema;
			$source=array(SS_DOCTRINE_SCHEMA_PATH.DIRECTORY_SEPARATOR.'slipstream.yml',SITE_DOCTRINE_SCHEMA_PATH.DIRECTORY_SEPARATOR.'site.yml');
		}
		$this->schema=$this->load($source);
		$this->save();
		return $this->schema;
	}
	
	public function get($type=null){
		if(is_null($type)) $type='schema';
		if(!is_null($this->{$type})) return $this->{$type};
		return $this->schema();
	}
	
	protected function load($source){
		$_merge=array();
		foreach($source as $_file){
			if(file_exists($_file)){
				$this->dispatch->output("Loading file: {$_file}");
				$_merge=array_merge_recursive($_merge,Spyc::YAMLLoad($_file));
			} else {
				$this->dispatch->output("Unable to load file: {$_file}");
			}
		}
		return $_merge;
	}
	
	protected function save(){
		if(count($this->schema)>0){
			$_schema=$this->schema;
			foreach($_schema as $class=>$data){
				if(isset($data['slipstream'])){;
					unset($_schema[$class]['slipstream']);
				}
			}
			file_put_contents(SITE_DOCTRINE_SCHEMA_PATH.DIRECTORY_SEPARATOR.'merge'.DIRECTORY_SEPARATOR.'merge.yml',Spyc::YAMLDump($_schema));
			//if(isset($_schema[$class]['slipstream'])) unset($_schema[$class]['slipstream']);
		}
	}
}
?>